from multiprocessing import shared_memory

shm_a = shared_memory.SharedMemory(name="test-liuj11",create=True, size=10)
buffer = shm_a.buf
len(buffer)
'10'

bytearray([1,2,3,4])
"bytearray(b'\x01\x02\x03\x04')"

buffer[:4] = bytearray([1,2,3,4])
buffer[4] = 100

# 指向同一块内存
shm_b = shared_memory.SharedMemory(shm_a.name)
shm_c = shared_memory.SharedMemory(name="test-liuj11")

# 1.查看
import array
print("shm_b:",array.array('b',shm_b.buf[:5]))
print("shm_c:",array.array('b',shm_c.buf[:5]))

# 2.修改
shm_b.buf[:5] = b'hello'
print("shm_b:",bytes(shm_b.buf[:5]))

shm_c.buf[5:10] = b'56789'
print("shm_a:",bytes(shm_a.buf[:10]))

# 3.越界访问
# shm_a.buf[10] = 100  # NOTE: out of bounds
# shm_a.buf[22] = 100  # NOTE: out of bounds

shm_a.close()
shm_b.close()
shm_c.close()

shm_a.unlink()
# shm_b.unlink()    # NOTE: 重复删除异常
# shm_c.unlink()

""" 运行
shm_b: array('b', [1, 2, 3, 4, 100])
shm_c: array('b', [1, 2, 3, 4, 100])
shm_b: b'hello'
shm_a: b'hello56789'

"""